package com.gitee.wsl.collections.iterator


class AggregateIterator<S, R>(
    private val iterator: Iterator<S>, 
    private val aggregator: AggregateOperator<S, R>
) : Iterator<R> {
    interface AggregateOperator<S, R> {
        fun aggregate(value: S): R

        val finalResult: R
    }

     override fun hasNext(): Boolean {
        return iterator.hasNext()
    }

     override fun next(): R {
        if (!hasNext()) {
            throw NoSuchElementException()
        }

        while (iterator.hasNext()) {
            val value = iterator.next()
            val result = aggregator.aggregate(value)
            if (result != null) {
                return result
            }
        }

        return aggregator.finalResult
    }
}